package com.cskaoyan.gateway.controller.user;


import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.RegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class RegisterController {

    @Reference(timeout = 3000,check = false)
    RegisterService registerService;
    //用来验证验证码
    @Reference
    IKaptchaService kaptchaService;

    //注册
    @Anoymous
    @RequestMapping("/user/register")
    public ResponseData userRegister(@RequestBody Map<String,String> map, HttpServletRequest request){
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String email = map.get("email");
        String captcha = map.get("captcha");
        //验证验证码,先从cookie中取出然后验证
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest codeRequest = new KaptchaCodeRequest();
        codeRequest.setUuid(uuid);
        codeRequest.setCode(captcha);
        //用validateKaptchaCode来验证，然后判断返回信息是否和设定的成功一样
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode(codeRequest);
        //String code = response.getImageCode();
        String responseCode = response.getCode();
       // String successCode = SysRetCodeConstants.SUCCESS.getCode();
        //不一样的话就返回验证码失败的信息
        if (!responseCode.equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg("验证码不正确");
        }
        //封装到UserRegisterRequest里，UserRegisterRequest内会对账号密码做一个非空判断
        UserRegisterRequest userRequest = new UserRegisterRequest();
        userRequest.setUserName(userName);
        userRequest.setUserPwd(userPwd);
        userRequest.setEmail(email);
        int ant = registerService.insertUser(userRequest);
        if (ant == 404){
            return new ResponseUtil<>().setErrorMsg("此邮箱已注册");
        }else if (ant == 405){
            return new ResponseUtil<>().setErrorMsg("用户名已存在");
        }
        UserRegisterResponse num = registerService.insertUserVerify(userRequest,uuid);
        return new ResponseUtil<>().setData(num);
    }

}
